package com.shujia.custom;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;

public class UDTFDemo2 extends GenericUDTF {

    /*
        initialize方法中我们要定义输出的类型和字段值名

        举例：b,11,12,13,14,15,16,17,18,19,20,21,22

        输出：
            b   0时  11
            b   2时  12
            ...
            b   24时 22
     */
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        //创建一个List集合存储结果列的名字
        ArrayList<String> colNames = new ArrayList<>();
        //创建一个集合存储每一列的数据类型
        ArrayList<ObjectInspector> colTypes = new ArrayList<>();

        //向集合中添加元素，设置列的名字以及类型
        colNames.add("id");
        colTypes.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        colNames.add("time");
        colTypes.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        colNames.add("idValue");
        colTypes.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        //返回一个对象，该对象封装了列的名字以及列的类型
        return ObjectInspectorFactory.getStandardStructObjectInspector(colNames, colTypes);
    }

    /*
        最重要的实现方法，将输入进来的数据，按照initialize方法的格式转换输出
        args: 接收将来函数调用时传入的参数

        将来需要使用forward函数将每一行输出，这里需要将输出一行的每一列数据封装成一个数组
     */
    @Override
    public void process(Object[] args) throws HiveException {
        //定义一个数组
        String[] cols = new String[3];

        //b,11,12,13,14,15,16,17,18,19,20,21,22
        //select lgFunc(id,col1,col2,...,col12) from xxx;
        cols[0] = args[0].toString();
        int d = 0;
        for (int i = 1; i < args.length; i++) {
            cols[1] = d + "时";
            cols[2] = args[i].toString();
            forward(cols);
            d += 2;
        }
    }

    @Override
    public void close() throws HiveException {
        //释放initialize方法中创建的资源
    }
}
